<template>
  <div
    id="resource_import"
    class="dialog animated"
    :class="open? 'fadeIn':'fadeOut'"
    v-show="show"
    :style="{visibility: (visible?'visible':'hidden')}"
  >
    <div class="panel animated" :class="open ? 'zoomIn' : ''">
      <div class="title">
        新增资源
        <div class="close" @click="cancel()"></div>
      </div>
      <div class="uploadcontent">
        <el-menu
          :default-active="activeIndex"
          class="el-menu-demo"
          mode="horizontal"
          @select="handleSelect"
        >
          <el-menu-item index="1" style="width:50%;text-align: center;">
            <span class="spanlabel">资源文件上传</span>
          </el-menu-item>
          <el-menu-item index="2" style="width:50%;text-align: center;">
            <span class="spanlabel">H5课件URL上传</span>
          </el-menu-item>
        </el-menu>
        <div class="form" v-show="activeIndex==1">
          <div>
            <input type="file" id="file" hidden />
          </div>
          <div class="tip">温馨提示：如需上传h5页面，请先将整个文件夹压缩成zip格式再上传。</div>
          <div class="btn_div" style="width:2rem;">
            <div
              class="btn_sure"
              @click="selectFile()"
              style="width:2rem;border-radius: 0.1rem;"
            >选择资源文件并上传</div>
          </div>
        </div>
        <div class="uploadurl" v-show="activeIndex==2">
          <div class="upload-box">
            <el-input
              v-model="h5filename"
              ref="h5filename"
              placeholder="请输入H5课件名称"
              style="width:100%;"
            ></el-input>
          </div>
          <div class="upload-box">
            <el-input v-model="fileurl" ref="fileurl" placeholder="请输入H5课件URL,以http://或https://开头" style="width:100%;"></el-input>
          </div>
          <div class="btnPanel">
            <div class="btnOk" @click="uploadOk">确定并上传</div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>
<script>
var vm, $file;
export default {
  data: function() {
    return {
      show: false,
      open: false,
      visible: false,
      fileName: "",
      activeIndex: "1",
      h5filename: "",
      fileurl: "",
      isFirst: true,
      uploader: null, //web直传服务
      baseUrl: "", //文件夹路径
      bosInfo: {}, //bos信息
      resourceParentId: "", //父资源id
      loading: null, //等待框
      currentFileList: [], //当前需要上传的文件集合
      isFrom: false //是机构上传还是校区上传
    };
  },
  methods: {
    init: function(data) {
      vm.show = true;
      setTimeout(function() {
        vm.open = true;
        vm.visible = true;
      }, 50);
      //文件在Bos的路径
      vm.baseUrl = data.bosBaseUrl;
      vm.isFirst = true;
      //文件资源ID
      vm.resourceParentId = data.resourceParentId;
      vm.isFrom = data.isFrom == "2" ? false : true;

      let paras = {
        tempAccessKeyId: vm.bosInfo.accessKeyId,
        tempSecretAccessKey: vm.bosInfo.secretAccessKey,
        tempSessionToken: vm.bosInfo.sessionToken
      };
      //校验stsToken
      api.checkValidityOfSTSToken(paras).then(function(data) {
        if (data.resultCode == 2000) {
          //如果token失效，则保存新的token
          if (data.info.validityOfStsToken) {
            data.info.bosStsTokenInfo.minFileSize = vm.bosInfo.minFileSize;
            data.info.bosStsTokenInfo.maxFileSize = vm.bosInfo.maxFileSize;
            vm.bosInfo = data.info.bosStsTokenInfo;
            //保存到缓存
            tool.setItem(lsKey.stsToken, data.info.bosStsTokenInfo, true);
            vm.uploader = null;
          }
          vm.getUpLoader();
        } else {
          vm.$message.error(data.message);
        }
      });
    },
    /**
     * 获取服务
     */
    getUpLoader() {
      vm.uploader = new baidubce.bos.Uploader({
        browse_button: "#file",
        bos_bucket: vm.bosInfo.bucketName, //bucket名
        bos_endpoint: vm.bosInfo.endpoint, //域名
        bos_ak: vm.bosInfo.accessKeyId, //临时ak
        bos_sk: vm.bosInfo.secretAccessKey, //临时sk
        uptoken: vm.bosInfo.sessionToken, //临时token
        max_file_size: "5Gb", //最大上传大小
        bos_multipart_min_size: "500M", //分块上传最小文件大小
        chunk_size: "100M", //分块上传每块上传的大小
        max_retries: 2, //上传失败重试次数
        init: {
          PostInit: function() {
            // uploader 初始化完毕之后，调用这个函数
            console.log("uploader 初始化完毕之后");
          },
          Key: function(_, file) {
            console.log("上传之前", file);
            // file.name =

            return vm.baseUrl + file.name;
          },
          FilesAdded: function(_, files) {
            // 当文件被加入到队列里面，调用这个函数
            console.log("文件被加入FilesAdded", files);
          },
          FilesFilter: function(_, files) {
            console.log("过滤FilesFilter", files);
            // 如果需要对加入到队列里面的文件，进行过滤，可以在
            // 这个函数里面实现自己的逻辑
            // 返回值需要是一个数组，里面保留需要添加到队列的文件
          },
          FileUploaded: function(_, file, info) {
            var param = new FormData();
            // if (file.type == "video/mp4") {
            //   param.append("file", file);
            //   vm.loading.text = "正在解析中...";
            // }
            param.append("bosResourceUrl", vm.baseUrl + file.name);
            param.append("resourceParentId", vm.resourceParentId);
            param.append("resourceName", file.name);
            param.append("resourceSize", file.size);
            // debugger;
            if (!vm.isFrom) {
              param.append("campusId", vm.$store.state.campusId);
            }
            api.resourceAdd(param).then(function(data) {
              if (data.resultCode == 2000) {
                tool.message({
                  showClose: true,
                  message: "上传成功",
                  type: "success"
                });
                vm.loading.close();
                vm.cancel();
              } else {
                vm.$message.error(data.message);
                vm.loading.close();
                vm.cancel();
              }
            });
          },
          UploadComplete: function() {
            console.log("上传结束");
            // vm.loading.close();
            // vm.cancel();
          },
          BeforeUpload: function(_, file) {
            console.log("上传初始化", file);
            if (file.type.indexOf("zip") != -1) {
              return false;
            }
            vm.loading = vm.$loading({
              text: "努力上传中...0%",
              spinner: "el-icon-loading",
              background: "rgba(0, 0, 0, 0.7)"
            });
            // 当某个文件开始上传的时候，调用这个函数
            // 如果想组织这个文件的上传，请返回 false
          },
          UploadProgress: function(_, file, progress, event) {
            var re = /([0-9]+\.[0-9]{2})[0-9]*/;
            let bosProgress = Math.round(progress * 100) / 100;
            vm.loading.text =
              "努力上传中..." + parseInt(bosProgress * 100) + "%";
            // 文件的上传进度
          },
          NetworkSpeed: function(_, bytes, time, pendings) {
            var speed = bytes / time; // 上传速度
            var leftTime = pendings / speed; // 剩余时间
          },
          UploadPartProgress: function(_, file, progress, event) {
            // 分片上传的时候，单个分片的上传进度
          },
          ChunkUploaded: function(_, file, result) {
            // 分片上传的时候，单个分片上传结束
          },
          Error: function(_, error, file) {
            console.log("上传失败", error);
            // 如果上传的过程中出错了，调用这个函数
            tool.message({
              showClose: true,
              message: "上传失败，请刷新页面再试！",
              type: "error"
            });
            vm.cancel();
          },
          UploadResume: function(_, file, partList, event) {
            // 断点续传生效时，调用这个函数，partList表示上次中断时，已上传完成的分块列表
          },
          UploadResumeError: function(_, file, error, event) {
            // 尝试进行断点续传失败时，调用这个函数
          }
        }
      });
    },
    /**
     *上传选项
     */
    handleSelect(key, keyPath) {
      vm.activeIndex = key + "";
    },
    initInput: function() {
      $file = $("#file");
      $file.change(function() {
        vm.fileName = $file[0].files[0].name;
        vm.importFile();
      });
    },
    cancel: function() {
      //隐藏弹窗
      vm.open = false;
      if ($file) {
        //清空文件名和文件输入框
        $file.val("");
        $file = null;
        vm.fileName = "";
      }
      setTimeout(function() {
        vm.show = false;
        vm.visible = false;
        vm.h5filename = "";
        vm.fileurl = "";
      }, 500);
      vm.$emit("callback");
    },
    sure: function() {
      vm.show = false;
    },
    selectFile: function() {
      if (!$file) {
        vm.initInput();
      }
      $file.val("");
      $file.click();
    },
    uploadOk() {
      var rules = [];
      let h5filename = this.$refs.h5filename;
      let fileurl = this.$refs.fileurl;
      rules.push({
        judge: vm.h5filename,
        focus: h5filename,
        tips: "请输入H5课件名称"
      });
      console.log(vm.fileurl.length);
      rules.push({
        judge: vm.fileurl,
        focus: fileurl,
        tips: "请输入H5课件URL"
      });
      rules.push({
        judge: vm.fileurl.length < 500,
        focus: fileurl,
        tips: "请输入不大于500长度的H5课件URL"
      });
      if (!tool.validate(rules)) {
        return;
      }
      vm.loading = vm.$loading({
        text: "正在上传",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)"
      });
      //上传到服务器
      var param = new FormData();
      param.append("bosResourceUrl", vm.fileurl);
      param.append("resourceParentId", vm.resourceParentId);
      param.append("resourceName", vm.h5filename + ".url");
      param.append("resourceSize", 0);
      if (!vm.isFrom) {
        param.append("campusId", vm.$store.state.campusId);
      }
      // param.append("campusId",vm.$store.state.campusId);

      var config = {
        headers: { "Content-Type": "multipart/form-data" },
        timeout: 2000000,
        onUploadProgress: function(e) {
          console.log(e);
          //属性lengthComputable主要表明总共需要完成的工作量和已经完成的工作是否可以被测量
          //如果lengthComputable为false，就获取不到e.total和e.loaded
          if (e.lengthComputable) {
            var rate = e.loaded / e.total; //已上传的比例
            if (rate <= 1) {
              //这里的进度只能表明文件已经上传到后台，但是后台有没有处理完还不知道
              //因此不能直接显示为100%，不然用户会误以为已经上传完毕，关掉浏览器的话就可能导致上传失败
              //等响应回来时，再将进度设为100%
              vm.loading.text =
                "正在上传 " +
                vm.h5filename +
                " ，已上传" +
                parseInt(rate * 100) +
                "%";
            }
          }
        }
      };

      api.resourceAdd(param, config).then(function(data) {
        if (data.resultCode == 2000) {
          tool.message({
            showClose: true,
            message: "上传成功",
            type: "success"
          });
          vm.loading.close();
          vm.cancel();
        } else {
          vm.$message.error(data.message);
          vm.loading.close();
          vm.cancel();
        }
      });
    },
    importFile: function() {
      if (vm.fileName == "") {
        tool.message({
          message: "请先选择文件",
          type: "warning"
        });
        return;
      }
      if (vm.bosInfo.minFileSize > $file[0].files[0].size) {
        tool.message({
          message: "上传的文件大小不小于2KB",
          type: "warning"
        });
        vm.cancel();
        return;
      }
      if ($file[0].files[0].type.indexOf("zip") != -1) {
        if (vm.isFirst) {
          //因为BOS不能清除input  所以在这里判断是否是第一次进入，若不是 直接返回
          vm.isFirst = false;
        } else {
          return;
        }
        console.log("zip上传");
        vm.loading = vm.$loading({
          text: "正在上传",
          spinner: "el-icon-loading",
          background: "rgba(0, 0, 0, 0.7)"
        });
        //上传到服务器
        var param = new FormData();
        param.append("file", $file[0].files[0]);
        param.append("bosResourceUrl", vm.baseUrl + $file[0].files[0].name);
        param.append("resourceParentId", vm.resourceParentId);
        param.append("resourceName", $file[0].files[0].name);
        param.append("resourceSize", $file[0].files[0].size);
        // param.append("campusId",vm.$store.state.campusId);

        var config = {
          headers: { "Content-Type": "multipart/form-data" },
          timeout: 2000000,
          onUploadProgress: function(e) {
            console.log(e);
            //属性lengthComputable主要表明总共需要完成的工作量和已经完成的工作是否可以被测量
            //如果lengthComputable为false，就获取不到e.total和e.loaded
            if (e.lengthComputable) {
              var rate = e.loaded / e.total; //已上传的比例
              if (rate <= 1) {
                //这里的进度只能表明文件已经上传到后台，但是后台有没有处理完还不知道
                //因此不能直接显示为100%，不然用户会误以为已经上传完毕，关掉浏览器的话就可能导致上传失败
                //等响应回来时，再将进度设为100%
                vm.loading.text =
                  "正在上传 " +
                  $file[0].files[0].name +
                  " ，已上传" +
                  parseInt(rate * 100) +
                  "%";
              }
            }
          }
        };

        api.resourceAdd(param, config).then(function(data) {
          if (data.resultCode == 2000) {
            tool.message({
              showClose: true,
              message: "上传成功",
              type: "success"
            });
            vm.loading.close();
            vm.cancel();
          } else {
            vm.$message.error(data.message);
            vm.loading.close();
            vm.cancel();
          }
        });
        // setTimeout(function() {
        //   vm.loading.close();
        //   vm.cancel();
        // }, 2000000);
      } else {
        //上传到Bos
        vm.uploader.start();
      }
    }
  },
  mounted: function() {
    vm = this;
    let stsToken = tool.getItem(lsKey.stsToken, true); //百度云信息
    vm.bosInfo = stsToken;
    if (vm.bosInfo && vm.bosInfo != null) {
      vm.getUpLoader();
    } else {
      tool.message({
        showClose: true,
        message: "系统内部出错，请联系管理员",
        type: "error"
      });
    }
  }
};
</script>
<style scoped src="@/style/module/dialog.css"></style>
<style lang="scss">
#resource_import {
  .uploadcontent {
    width: 100%;
    padding: 0rem 0.3rem;

    .uploadfile {
      width: 100%;
      height: 0.75rem;
      line-height: 1rem;
      text-align: center;
      .upload-box {
        .uploadbtn {
          padding: 0.08rem 0.5rem;
          color: #ffffff;
          cursor: pointer;
          width: 1rem;
          height: 0.36rem;
          background: #5f9df9;
          border-radius: 0.05rem;
        }
        .file {
          position: relative;
          background: #d0eeff;
          border: 1px solid #99d3f5;
          border-radius: 0.3rem;
          overflow: hidden;
          color: rgb(0, 148, 255);
          text-decoration: none;
          text-indent: 0;
          line-height: 20px;
          background: none;
          border: none;
        }
        .file input {
          position: absolute;
          font-size: 100px;
          right: 0;
          top: 0;
          opacity: 0;
        }
      }
    }
    .uploadurl {
      width: 100%;
      height: 1.9rem;
      .upload-box {
        margin-top: 0.2rem;
        .el-input__inner {
          border-radius: 0.05rem;
          font-size: 0.16rem;
          color: #666666;
          height: 0.36rem !important;
          line-height: 0.36rem;
        }
      }
    }
  }
  .btnPanel {
    width: 100%;
    height: 1rem;
    display: inline-flex;
    line-height: 1rem;
    justify-content: center;
    align-items: center;
    .btnOk {
      width: 1.6rem;
      height: 0.4rem;
      font-size: 0.16rem;
      background: #3885f8;
      color: #ffffff;
      border-radius: 0.1rem;
      line-height: 0.4rem;
      text-align: center;
      cursor: pointer;
    }
    .btnOk:hover {
      background: rgba(56, 133, 248, 0.8);
    }
    .btnCancel {
      width: 1.6rem;
      height: 0.4rem;
      font-size: 0.16rem;
      background: #ffffff;
      border-radius: 0.1rem;
      color: #333333;
      border: 0.01rem solid #c0c4cc;
      line-height: 0.4rem;
      text-align: center;
      cursor: pointer;
    }
    .btnCancel:hover {
      background: rgba(56, 133, 248, 0.1);
    }
  }
}
</style>
<style scoped>
.panel {
  width: 6rem;
  padding: 0rem 0.2rem;
}

.btn_div {
  width: 2rem;
  padding: 0.2rem 0;
}

.btn_sure {
  width: 2rem;
  margin-right: 0;
}

.form {
  padding: 0.1rem 0rem;
  font-size: 0.16rem;
  color: #666666;
}

.select_btn {
  width: 1.2rem;
  height: 0.36rem;
  line-height: 0.36rem;
  color: white;
  background-color: #3885f8;
  margin-right: 0.15rem;
  float: right;
  font-size: 0.16rem;
  text-align: center;
  border-radius: 0.08rem;
  cursor: pointer;
  user-select: none;
}

.select_btn:active {
  background-color: rgba(56, 133, 248, 0.8);
}

.tip {
  padding-top: 0.12rem;
  padding-left: 0rem;
  color: #999999;
}

.clue_model {
  text-decoration: underline;
  color: #0000ff;
  cursor: pointer;
}
</style>
